<template>
  <div
    class="apps flex-1 p-12"
    ref="apps"
    data-selection-area
    @contextmenu="openContextMenu"
    :style="style"
  >
    <ul ref="appRef">
      <li
        :data-selection="item.id"
        v-for="item in userRouters"
        :key="item.name"
        :class="{
          selected: selectedKeys.includes(item.id),
        }"
        @click="select(item)"
        @dblclick="openApp(item)"
        v-show="!item.hidden"
        @contextmenu.stop="onContextmenu(item)"
      >
        <div>
          <div class="logo">
            <AxImage
              :src="getIconByName(item) || logoPng"
              :draggable="false"
              :width="30"
              :height="30"
            />
          </div>
          <div class="title">{{ item?.title || 'Untitled' }}</div>
        </div>
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import type { Routers } from '@/api/modules/system/user/types';
import logoPng from '@/assets/logo.png';
import usePageStore from '@/store/page';
import { selectionKeys } from '@/views/selector/selection/data';
import { useSortable } from '@vueuse/integrations/useSortable';
import { appContextMenu, openContextMenu } from './contextmenu';
import { getIconByName, openApp, userRouters } from './data';

const selectedKeys = ref<number[]>([]);
const appRef = ref();

const appHeight = ref(96);
const apps = ref<HTMLElement>();

onMounted(async () => {
  nextTick(() => {
    useSortable(appRef, userRouters, {
      animation: 200,
    });
  });
});

const select = (item: Routers) => {
  selectedKeys.value = [item.id];
};
const onContextmenu = (item: Routers) => {
  select(item);
  appContextMenu(item);
};
const pageStore = usePageStore();

const style = computed(() => {
  return {
    backdropFilter: `blur(${pageStore.$state.theme.background.blur}px)`,
    height: `${window.innerHeight - appHeight.value}px`,
  };
});

watch(
  selectionKeys,
  () => {
    selectedKeys.value = Array.from(selectionKeys.value).map(e => Number(e));
  },
  {
    deep: true,
  },
);
</script>

<style lang="scss" scoped>
@import './apps.scss';
</style>
